using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEditor;

namespace EntityKit.Editor
{
    public static class ScriptableObjectHelper
    {
        public static T LoadOrCreateSingletonScriptableObject<T>(string savePath) where T : ScriptableObject
        {
            var so = LoadSingletonScriptableObject<T>();
            if (so == null)
            {
                so = CreateSingletonScriptableObject<T>(savePath);
            }

            return so;
        }

        public static T LoadSingletonScriptableObject<T>() where T : ScriptableObject
        {
            var guids = AssetDatabase.FindAssets($"t:{typeof(T).Name}");
            if (guids.Length == 0)
                return null;
            if (guids.Length > 1)
            {
                var sb = new StringBuilder();
                foreach (var guid in guids)
                {
                    sb.AppendLine(AssetDatabase.GUIDToAssetPath(guid));
                }

                throw new System.Exception($"多个{typeof(T).Name}存在项目中，请检查 {sb.ToString()}");
            }

            var path = AssetDatabase.GUIDToAssetPath(guids[0]);
            return AssetDatabase.LoadAssetAtPath<T>(path);
        }

        public static bool HasSingletonScriptableObject<T>() where T : ScriptableObject
        {
            var guids = AssetDatabase.FindAssets($"t:{typeof(T).Name}");
            return guids.Length > 0;
        }

        public static T CreateSingletonScriptableObject<T>(string savePath) where T : ScriptableObject
        {
            var so = ScriptableObject.CreateInstance<T>();
            EnsureDirectoryExists(savePath);
            var type = typeof(T);
            AssetDatabase.CreateAsset(so, savePath);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            return so;
        }

        private static void EnsureDirectoryExists(string path)
        {
            var directory = Path.GetDirectoryName(path);
            if (Directory.Exists(directory)) return;
            Directory.CreateDirectory(directory);
            AssetDatabase.Refresh();
        }
    }
}